<template>
  <ContentField>
    <!-- Modal -->
    <div class="modal fade modal-xl" id="add-bot-btn" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" style="color: white">创建一个新的Bot</h1>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label for="add-bot-title" class="form-label">名称</label>
              <input
                v-model="botadd.title"
                type="text"
                class="form-control"
                id="add-bot-title"
                placeholder="请输入Bot名称" />
            </div>
            <div class="mb-3">
              <label for="add-bot-description" class="form-label">Bot简介</label>
              <textarea
                v-model="botadd.description"
                class="form-control"
                id="add-bot-description"
                rows="2"
                placeholder="描述你的Bot"></textarea>
            </div>
            <div class="mb-3">
              <label for="add-bot-code" class="form-label">Bot代码</label>
              <VAceEditor
                v-model:value="botadd.content"
                @init="editorInit"
                lang="c_cpp"
                theme="textmate"
                :options="{ fontSize: 18 }"
                style="height: 220px" />
            </div>
          </div>
          <div class="modal-footer">
            <!-- <div class="error_message">{{ botadd.error_message }}</div> -->
            <button type="button" class="btn btn-outline-info" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-outline-info" @click="add_bot">创建</button>
          </div>
        </div>
      </div>
    </div>

    <div class="container">
      <div class="row">
        <div class="col-3 animate__animated animate__bounceInDown">
          <div class="card" style="margin-top: 20px">
            <div class="card-body">
              <div class="d-flex justify-content-center align-items-center">
                <button
                  type="button"
                  class="btn btn-outline-info"
                  style="width: 100%; margin-bottom: 5%"
                  @mouseenter="showUsername"
                  @mouseleave="hideUsername"
                  data-bs-toggle="modal"
                  data-bs-target="#update-username">
                  {{ buttonText }}
                </button>
              </div>
              <img
                :src="$store.state.user.photo + '?random=' + Math.random()"
                alt=""
                style="width: 100%; border-radius: 5px" />
              <div class="d-flex justify-content-center align-items-center">
                <input
                  type="file"
                  id="file-upload"
                  style="display: none"
                  @change="handleFileUpload" />
                <button
                  class="btn btn-outline-info"
                  style="width: 100%; margin-top: 5%"
                  @click="openFileUploadDialog">
                  更新头像
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="col-9">
          <div class="card" style="margin-top: 20px">
            <div class="card-header animate__animated animate__bounceInDown">
              <span style="font-size: 130%; color: white">我的Bots</span>
              <button
                type="button"
                class="btn btn-outline-info float-end"
                data-bs-toggle="modal"
                data-bs-target="#add-bot-btn">
                + 创建一个新的Bot
              </button>
            </div>

            <div class="card-body">
              <table class="table custom-table">
                <thead>
                  <tr>
                    <th class="col-3">名称</th>
                    <th class="col-3">描述</th>
                    <th class="col-4">创建时间</th>
                    <th class="col-2">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="bot in bots" :key="bot.id" class="selected-row">
                    <td>{{ bot.title }}</td>
                    <td>{{ bot.description }}</td>
                    <td>{{ bot.createtime }}</td>
                    <td>
                      <button
                        type="button"
                        class="btn btn-outline-info"
                        style="margin-right: 5px"
                        data-bs-toggle="modal"
                        :data-bs-target="'#update-bot-modal-' + bot.id">
                        修改
                      </button>
                      <button type="button" class="btn btn-delete" @click="remove_bot(bot)">
                        删除
                      </button>

                      <!-- Modal -->
                      <div
                        class="modal fade modal-xl"
                        :id="'update-bot-modal-' + bot.id"
                        tabindex="-1">
                        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                          <div class="modal-content">
                            <div class="modal-header">
                              <h1 class="modal-title fs-5" style="color: white">修改Bot</h1>
                              <button
                                type="button"
                                class="btn-close"
                                data-bs-dismiss="modal"
                                aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                              <div class="mb-3">
                                <label for="add-bot-title" class="form-label">名称</label>
                                <input
                                  v-model="bot.title"
                                  type="text"
                                  class="form-control"
                                  id="add-bot-title"
                                  placeholder="请输入Bot名称" />
                              </div>
                              <div class="mb-3">
                                <label for="add-bot-description" class="form-label">Bot简介</label>
                                <textarea
                                  v-model="bot.description"
                                  class="form-control"
                                  id="add-bot-description"
                                  rows="2"
                                  placeholder="描述你的Bot"></textarea>
                              </div>
                              <div class="mb-3">
                                <label for="add-bot-code" class="form-label">Bot代码</label>
                                <VAceEditor
                                  v-model:value="bot.content"
                                  @init="editorInit"
                                  lang="c_cpp"
                                  theme="textmate"
                                  :options="{ fontSize: 20 }"
                                  style="height: 220px" />
                              </div>
                            </div>
                            <div class="modal-footer">
                              <!-- <div class="error_message">{{ bot.error_message }}</div> -->
                              <button
                                type="button"
                                class="btn btn-outline-info"
                                data-bs-dismiss="modal">
                                取消
                              </button>
                              <button
                                type="button"
                                class="btn btn-outline-info"
                                @click="update_bot(bot)">
                                保存修改
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="col-12 d-flex justify-content-center align-items-center user-logout animate__animated animate__bounceInUp">
      <div class="col-6 d-flex justify-content-center align-items-center">
        <button type="button" class="btn btn-delete" @click="logout">LOGOUT</button>
      </div>
    </div>

    <div class="modal fade modal-sm" id="update-username" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" style="color: white">更新昵称</h1>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label for="update-user-name" class="form-label"></label>
              <input
                v-model="newUsername"
                type="text"
                class="form-control"
                id="update-user-name"
                placeholder="请输入新的昵称" />
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-info" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-outline-info" @click="updateUsername">
              确认更改
            </button>
          </div>
        </div>
      </div>
    </div>
  </ContentField>
</template>

<script>
import { ref, reactive } from "vue";
import $ from "jquery";
import { useStore } from "vuex";
import router from "@/router/index";
import { Modal } from "bootstrap/dist/js/bootstrap";
import { VAceEditor } from "vue3-ace-editor";
import ace from "ace-builds";
import ContentField from "@/components/ContentField.vue";
import { toast } from "vue3-toastify";

export default {
  components: {
    VAceEditor,
    ContentField,
  },
  setup() {
    ace.config.set(
      "basePath",
      "https://cdn.jsdelivr.net/npm/ace-builds@" +
        require("ace-builds").version +
        "/src-noconflict/"
    );

    const store = useStore();
    let bots = ref([]);

    const botadd = reactive({
      title: "",
      description: "",
      content: "",
      error_message: "",
    });

    const refresh_bots = () => {
      $.ajax({
        url: "http://127.0.0.1:3000/user/bot/getlist/",
        type: "get",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        success(resp) {
          bots.value = resp;
        },
      });
    };

    refresh_bots();

    const add_bot = () => {
      // botadd.error_message = "";
      $.ajax({
        url: "http://127.0.0.1:3000/user/bot/add/",
        type: "post",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        data: {
          title: botadd.title,
          description: botadd.description,
          content: botadd.content,
        },
        success(resp) {
          if (resp.error_message === "success") {
            toast("添加成功,派它出战吧~", {
              theme: "auto",
              type: "success",
              position: "top-center",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });

            botadd.title = "";
            botadd.description = "";
            botadd.content = "";
            Modal.getInstance("#add-bot-btn").hide();
            refresh_bots();
          } else {
            toast(resp.error_message, {
              theme: "auto",
              type: "warning",
              position: "top-center",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });
            // botadd.error_message = resp.error_message;
          }
        },
      });
    };

    const update_bot = (bot) => {
      // bot.error_message = "";
      $.ajax({
        url: "http://127.0.0.1:3000/user/bot/update/",
        type: "post",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        data: {
          bot_id: bot.id,
          title: bot.title,
          description: bot.description,
          content: bot.content,
        },
        success(resp) {
          if (resp.error_message === "success") {
            toast("修改成功,派它出战吧~", {
              theme: "auto",
              type: "success",
              position: "top-center",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });

            Modal.getInstance("#update-bot-modal-" + bot.id).hide();
            refresh_bots();
          } else {
            toast(resp.error_message, {
              theme: "auto",
              type: "warning",
              position: "top-center",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });
          }
        },
      });
    };

    const remove_bot = (bot) => {
      $.ajax({
        url: "http://127.0.0.1:3000/user/bot/remove/",
        type: "post",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        data: {
          bot_id: bot.id,
        },
        success(resp) {
          if (resp.error_message === "success") {
            toast("删除成功~", {
              theme: "auto",
              type: "success",
              position: "top-center",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });
            refresh_bots();
          }
        },
      });
    };

    // 退出登录
    const logout = () => {
      toast("退出登录", {
        theme: "auto",
        type: "success",
        position: "top-right",
        autoClose: 1000,
        hideProgressBar: true,
        dangerouslyHTMLString: true,
        transition: "slide",
      });

      setTimeout(() => {
        store.dispatch("logout");
        router.push({
          name: "user_account_login",
        });
      }, 1000);
    };

    // 更新头像
    const openFileUploadDialog = () => {
      const fileUpload = document.getElementById("file-upload");
      fileUpload.click();
    };

    // 先将图片转化为base64编码，然后发送给后端上传
    const handleFileUpload = (event) => {
      const selectedFile = event.target.files[0];
      const reader = new FileReader();

      reader.onload = () => {
        const base64Image = reader.result;
        // 在这里将base64Image传递给后端
        // 你可以在这里调用上传头像的函数，并将base64Image作为参数传递给后端
        // console.log("Base64 Image:", removeBase64Prefix(base64Image));
        // 调用上传图片函数
        uploadAvatar(removeBase64Prefix(base64Image));
      };

      reader.readAsDataURL(selectedFile);
    };

    // 去掉base64编码前缀
    function removeBase64Prefix(base64String) {
      return base64String.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
    }

    // 发送请求给后端，把选中图片的base64编码发送
    function uploadAvatar(base64Image) {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/uploadAvatar/",
        type: "post",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        data: {
          avatarData: base64Image,
          userId: store.state.user.id,
        },
        success(resp) {
          if (resp.error_message === "success") {
            // 如果成功，更新用户头像url，并添加一个时间戳作为查询参数
            const timestamp = Date.now(); // 生成一个唯一时间戳
            const imageUrl = resp.imageUrl + `?timestamp=${timestamp}`;
            // 如果成功，更新用户头像url
            store.commit("updataUserPhoto", imageUrl);

            // 通过全局组件方法显示提示消息
            toast("更新成功!", {
              theme: "auto",
              type: "success",
              position: "top-right",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });
          } else {
            toast("更新失败!", {
              theme: "auto",
              type: "error",
              position: "top-right",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });
          }
        },
      });
    }

    // 修改昵称
    const buttonText = ref(store.state.user.username);

    const showUsername = () => {
      buttonText.value = "更新昵称";
    };

    const hideUsername = () => {
      buttonText.value = store.state.user.username;
    };

    const newUsername = ref("");

    // 发送请求给后端，更新昵称
    function updateUsername() {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/updateUsername/",
        type: "post",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        data: {
          newUsername: newUsername.value,
          userId: store.state.user.id,
        },
        success(resp) {
          if (resp.error_message === "success") {
            toast("更新成功!", {
              theme: "auto",
              type: "success",
              position: "top-right",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });
            store.commit("updateUsername", newUsername.value);
            hideUsername();
            Modal.getInstance("#update-username").hide();
          } else {
            toast(resp.error_message, {
              theme: "auto",
              type: "warning",
              position: "top-center",
              autoClose: 1000,
              hideProgressBar: true,
              dangerouslyHTMLString: true,
              transition: "slide",
            });
          }
        },
      });
    }

    return {
      bots,
      botadd,
      buttonText,
      newUsername,
      add_bot,
      remove_bot,
      update_bot,
      logout,
      openFileUploadDialog,
      handleFileUpload,
      uploadAvatar,
      showUsername,
      hideUsername,
      updateUsername,
    };
  },
};
</script>

<style scoped>
div.error_message {
  color: red;
}

.card {
  background-color: transparent;
  border: 2px solid rgb(91, 94, 94);
}

.custom-table {
  background-color: transparent;
  color: white;
  /* border: 2px solid rgb(13, 202, 240); */
  border-collapse: separate;
  border-spacing: 0;
}

.custom-table th,
.custom-table td {
  border: 0px solid rgb(255, 255, 255);
  /* text-align: center; */
  padding: 8px;
}

.custom-table {
  color: rgb(255, 255, 255);
}

.selected-row:hover {
  color: rgb(13, 202, 240);
  background-color: rgba(50, 50, 50, 0.35);
}

button.btn:hover {
  color: white;
  animation: shake 0.5s;
}

.btn-delete {
  border-color: rgb(240, 66, 66);
  color: rgb(240, 66, 66);
}

.btn-delete:hover {
  background-color: rgb(240, 66, 66);
}

@keyframes shake {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.modal-content {
  background-color: rgba(46, 61, 74, 0.9);
  border-color: rgb(91, 94, 94);
}

.form-label {
  color: white;
}

label[for="add-bot-title"] {
  text-align: left;
}

.user-logout {
  position: fixed;
  bottom: 10%;
  left: 0;
  right: 0;
}
</style>
